package com.itheima.stargraph.service.impl;

import cn.hutool.json.JSONUtil;
import com.itheima.stargraph.pojo.ComfyuiTask;
import com.itheima.stargraph.pojo.MessageBase;
import com.itheima.stargraph.service.ComfyuiMsgService;
import com.itheima.stargraph.service.Text2ImageService;
import com.itheima.stargraph.service.WsNotifyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;

/**
 * 根据不同情况处理要推送给客户端的消息
 *
 * @Author mr.wu
 * @Date 2025-6-7 12:05
 */
@Service
public class ComfyuiMsgServiceImpl implements ComfyuiMsgService {


    /**
     * 类型：生图进度
     */
    private static final String TYPE_PROGRESS = "progress";

    /**
     * 类型：生图结果
     */
    private static final String TYPE_EXECUTED = "executed";

    /**
     * 类型：生图错误
     */
    private static final String TYPE_EXECUTION_ERROR = "execution_error";

    @Autowired
    private Text2ImageService text2ImageService;

    @Autowired
    private WsNotifyService wsNotifyService;

    /**
     * 根据不同情况处理要推送给客户端的消息
     *
     * @param messageBase
     */
    @Override
    public void handleMsg(MessageBase messageBase) {
        //处理进度消息
        String type = messageBase.getType();
        if (type.equals(TYPE_PROGRESS)){
            this.handlerProgress(messageBase);
        } else if (type.equals(TYPE_EXECUTED)) {
            this.handlerExecuted(messageBase);
        }  else if(type.equals(TYPE_EXECUTION_ERROR)) {
            handleExecutionError(messageBase);
        }

    }
    @Value("${comfyuiHost}")
    private String comfyuiHost;

    /**
     * 推送生图进度消息给前端
     */
    private void handlerProgress(MessageBase messageBase){

    }

    /**
     * 推送生图结果消息给前端
     */
    private void handlerExecuted(MessageBase messageBase){
        HashMap<String,Object> data = messageBase.getData();

        data.put("type",TYPE_PROGRESS);

        Object promptIdObj = data.getOrDefault("prompt_id", null);
        if (promptIdObj==null){
            return;
        }

        String promptId = String.valueOf(promptIdObj);
        ComfyuiTask comfyuiTask = text2ImageService.getStartedTask(promptId);
        String clientId = comfyuiTask.getWsClientId();
        wsNotifyService.sendToUser(clientId, JSONUtil.toJsonStr(data));
    }

    /**
     * 推送生图错误消息给前端
     */
    private void handleExecutionError(MessageBase messageBase){

    }


}